import platform
import os
import ctypes
import pathlib
import logging


def get_free_space_mb(folder):
    """ Return folder/drive free space (in bytes)

    """
    if platform.system() == 'Windows':
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))
        return free_bytes.value / 1024 / 1024
    else:
        st = os.statvfs(folder)
        return st.f_bavail * st.f_frsize / 1024 / 1024


def get_disk_free_plot_num(folder, k):
    free_space_gb = get_free_space_mb(folder) / 1024
    p = pathlib.Path(folder)
    plot_files = p.glob('*.plot')
    placeholder_files = p.glob('*.placeholder')
    plotids = [plot_file.name[-69:-5] for plot_file in plot_files]
    placeholder_sum = 0
    for placeholder_file in placeholder_files:
        pid = placeholder_file.name.split('.')[0]
        if pid in plotids:
            continue
        else:
            placeholder_sum += 1
    free_plot_space = free_space_gb // (101.1 * (k * 2 ** k) / (32 * 2 ** 32)) - placeholder_sum
    return free_plot_space, len(plotids)


def get_target_destination(destinations, k):
    max_plot_num = -1
    final_destination = None
    for destination in destinations:
        free_plot_num, plot_num = get_disk_free_plot_num(destination, k)
        logging.info(f'destination:{destination},free_plot_num:{free_plot_num},plot_num:{plot_num}')
        if free_plot_num > 0 and plot_num > max_plot_num:
            max_plot_num = plot_num
            final_destination = destination
    return final_destination


if __name__ == '__main__':
    free_plot_num, have_plot_num = get_disk_free_plot_num('L:/', 25)
    pass
